<!--
*  2021-03-15
*  成品信息
-->
<template>
  <div id="app" class="product-html">
    <!-- 头部导航 -->
    <van-nav-bar
      ref="header"
      :title="title"
      left-arrow
      @click-left="onClickLeft"
      left-text="返回"
    >
      <template #right>
        <span @click="onClickRight"><van-icon name="plus" size="20" /></span>
      </template>
    </van-nav-bar>
    <!-- 筛选 -->
    <van-search
      v-model="designNoLike"
      placeholder="请输入品号关键词"
      @search="onSearch"
    />
    <!-- 滚动 -->
    <better-scroll
      class="public-scroll"
      :data="tableData"
      :totalPage="totalPage"
    >
      <van-cell-group v-show="tableData.length !== 0">
        <van-swipe-cell v-for="(data, index) in tableData" :key="index">
          <van-cell title="成品品号" :value="data.topNo"></van-cell>
          <van-cell v-show="data.color" title="成品色号" :value="data.color"></van-cell>
          <van-cell v-if="data.designId > 0" title="成品经纬" :value="data.productLonNum + '*' + data.productLatNum"></van-cell>
          <van-cell v-if="data.designId > 0" title="成品门幅" :value="data.productWidth"></van-cell>
          <van-cell v-if="data.designId > 0" title="成品克重" :value="data.productWeight"></van-cell>
          <van-cell v-if="data.designId > 0" title="成品含量" :value="data.composition"></van-cell>
          <van-cell v-show="data.designSeqNo" title="成品匹号" :value="data.designSeqNo" :class="data.status > 90 ? 'status-out' : SPLIT_BLANK">
            <template #extra>
              <van-button v-if="data.status == 2" type="danger" size="mini" style="margin-left: 5vw;" @click="productClothOutByDestroyFn(data)">剪样销布</van-button>
              <van-button v-if="data.status == 94" type="warning" size="mini" style="margin-left: 5vw;" @click="productClothInByDestroyFn(data)">取消销布</van-button>
            </template>
          </van-cell>
          <van-cell v-show="data.dyeSeqNo" title="成品缸号" :value="data.dyeSeqNo"></van-cell>
          <van-cell v-show="data.length" title="成品长度" :value="data.length"></van-cell>
          <van-cell v-show="data.weight" title="成品重量" :value="data.weight"></van-cell>
          <van-cell v-show="data.width" title="成品幅宽" :value="data.width"></van-cell>
          <van-cell v-if="data.designId > 0" title="坯布样图"></van-cell>
          <van-row v-if="data.designId > 0" type="flex" justify="center">
              <van-image width="10rem" height="10rem" fit="contain" :src="samplePicPreview[0]" @click="showSamplePicPreViewFlag = true">
                <template v-slot:error>加载失败</template>
                <template v-slot:loading>
                  <van-loading type="spinner" size="20" />
                </template>
              </van-image>
          </van-row>
          <van-cell v-if="data.designId > 0" title="成品图">
            <template #default>
              <van-button v-permissions="',487_1245,10_54,57_58,'" type="warning" size="mini" icon="plus" @click="uploadProductPicFn(data.designId)">上传成品图</van-button>
            </template>
          </van-cell>
          <van-row v-if="data.designId > 0" type="flex" justify="center">
            <van-image width="10rem" height="10rem" fit="contain" :src="productPicPreview[0]" @click="showProductPicPreViewFlag = true">
              <template v-slot:error>加载失败</template>
              <template v-slot:loading>
                <van-loading type="spinner" size="20" />
              </template>
            </van-image>
          </van-row>
          <van-row v-if="data.designId > 0"  v-permissions="',487_1245,10_54,57_58,'" type="flex" justify="center">
            <van-uploader style="margin: 10px" preview-size="10rem" v-model="uploadFileList" :max-count="1"/>
          </van-row>
        </van-swipe-cell>
      </van-cell-group>
      <van-empty class="custom-image" image="https://img01.yzcdn.cn/vant/custom-empty-image.png" v-show="tableData.length === 0" description="暂无数据"></van-empty>
    </better-scroll>

    <van-popup v-model="show" position="bottom" get-container="body">
      <van-picker show-toolbar value-key="name" :columns="columns" @confirm="onConfirm" @cancel="show = false"></van-picker>
    </van-popup>

    <!-- 图片预览 -->
    <van-image-preview v-model="showSamplePicPreViewFlag" :showIndex="false" :closeable="true" :images="samplePicPreview" get-container=".public-scroll">
    </van-image-preview>
    <van-image-preview v-model="showProductPicPreViewFlag" :showIndex="false" :closeable="true" :images="productPicPreview">
    </van-image-preview>
  </div>
</template>

<script>
import { exportBaseUrl } from '@/utils/request';
import { comeBack } from "@/utils/index";
import { getUploadKey } from "@/api/public";
import {
  clothNoteDetail,
  filterDesignByNo,
  getProductInfo,
  editProductPic, productClothOutByDestroy, productClothInByDestroy,
} from "@/api/product";
import {SPLIT_BLANK} from "@/api/enum";

export default {
  name: "productHtml",
  data() {
    return {
      SPLIT_BLANK,
      title: "成品信息",
      totalPage: 1,
      tableData: [
          // {id:7948,designId:603,noteId:268,greyClothId:40046,designNo:"32738-2-单面短顺格子",designSeqNo:16,length:61.80,weight:42.00,miWeight:679.61,width:150.00,topNo:"32738",dyeSeqNo:"无",color:"2#",productLonNum:143,productLatNum:119,productComposition:"W(79%)    T(20%)    P(1%)",productWidth:150.00,productWeight:700.00,samplePic:"YPSJD/YPSJD_220315131414FyKbC_1.jpeg",productPic:""}
      ],
      designNoLike: "",
      show: false,
      columns: [],

      uploadFileList: [],
      showSamplePicPreViewFlag: false,
      samplePicPreview: [],
      showProductPicPreViewFlag: false,
      productPicPreview: []
    };
  },
  mounted() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      this.$nextTick(() => {
        that.initFn(that);
      });
    } else {
      window.apiready = function () {
        that.initFn(that);
      };
    }
  },
  methods: {
    //初始化
    initFn(that) {
      that.onClickRight();
      window.api.addEventListener({
        name:'viewdisappear'
      }, function() {
        window.api.closeWin();
      });
    },
    //重置
    resetProps(that) {
      that.designNoLike = "";
      that.tableData.splice(0, that.tableData.length);    //三方组件有问题 先用这个
      that.uploadFileList.splice(0, that.uploadFileList.length);    //上传文件置空
      that.samplePicPreview.splice(0, that.samplePicPreview.length);    //坯布样品图置空
      that.productPicPreview.splice(0, that.productPicPreview.length);    //成品图置空
    },
    // 返回
    onClickLeft() {
      comeBack();
    },
    // 扫码
    onClickRight() {
      const that = this;
      that.resetProps(that);
      const zyHmsScan = api.require('zyHmsScan');
      zyHmsScan.openDefaultView({}, ret => {
        if(ret.status) {
          let content = ret.result;
          if (content.indexOf(",") != -1) {
            that.$toast.fail("请扫成品二维码");
            return false;
          }

          let index = content.indexOf("flag");
          let flag = index != -1 ? 1 : "";
          let params = {};
          let lastIndex;
          if(flag) {
            let lastIndex2 = content.indexOf("?");
            if (content.indexOf("http://") >= 0) {
              lastIndex = content.lastIndexOf("/");
            } else {
              lastIndex = -1;
            }
            params.geryClothId = content.slice(lastIndex + 1, lastIndex2);
            params.flag = flag;
          } else {
            lastIndex = content.lastIndexOf("/");
            params.geryClothId = content.slice(lastIndex + 1, content.length);
          }

          clothNoteDetail(params, res => {
            if(res.designId) {
              res.composition = that.analyseComposition(that, res.productComposition);
              that.loadPics(that, res);
            }
            that.tableData.push(res);
          });
        }
      });
    },
    // 去掉空值
    trimSpace(array) {
      for (let i = 0; i < array.length; i++) {
        if (
          array[i] == "" ||
          array[i] == null ||
          typeof array[i] == "undefined"
        ) {
          array.splice(i, 1);
          i = i - 1;
        }
      }
      return array;
    },
    //计算成份
    analyseComposition(that, compositionStr) {
      let arr = that.trimSpace(compositionStr.split(" "));
      let composition = [];
      arr.forEach((item) => {
        let params = {};
        params.type = item.split("(")[0];
        params.content = item
            .split("(")[1]
            .slice(0, item.split("(")[1].length - 1);
        composition.push(params);
      });
      let n = "";
      composition.forEach((m) => {
        n += "," + that.$getCompositionName(m.type) + m.content;
      });
      return n.substr(1);
    },


    // 搜索
    onSearch() {
      filterDesignByNo({
        no: this.designNoLike,
      }, (res) => {
        if (res.length) {
          res.forEach(item => {
            item.name = (item.no + "-" + item.name);
          });
          this.columns = res;
          this.show = true;
        } else {
          this.$toast.fail("筛选无数据");
        }
      });
    },
    onConfirm(val) {
      this.resetProps(this);
      this.show = false;
      getProductInfo(val.id.toString(), (res) => {
        res.designId = res.id;
        res.topNo = val.no;
        res.composition = this.analyseComposition(this, res.productComposition);
        this.tableData.push(res);
        this.loadPics(this, res);
      });
    },

    //上传成品图
    uploadProductPicFn(designId) {
      let that = this;
      if(that.uploadFileList.length === 0) {
        that.$toast.fail("请拍照或者选择图片文件上传");
        return;
      }
      that.$toast.loading({
        message: '加载中...',
        forbidClick: true,
        loadingType: 'spinner',
      });

      //上传
      getUploadKey({
        type: "YPSJD"
      }, tokenRes => {
        let form = new FormData();
        form.append('files', that.uploadFileList[0].file);
        let oReqCos = new XMLHttpRequest();
        oReqCos.open('POST', exportBaseUrl("res") + '/file_upload/upload');
        oReqCos.setRequestHeader('x-yd-access-token', tokenRes.accessToken);
        oReqCos.onload = function () {
          if (oReqCos.status === 200) {
            let res = JSON.parse(oReqCos.response)
            if (res.code === 2000) {
              //更新设计单成品图
              editProductPic({
                designId: designId,
                picName: res.data
              }, () => {
                that.$toast.success("上传成功");
                that.showProductPicPreViewFlag = false;

                let URL = window.URL || window.webkitURL;
                let imgURL = URL.createObjectURL(that.uploadFileList[0].file);
                that.productPicPreview.splice(0, that.productPicPreview.length);
                that.productPicPreview.push(imgURL);
              });
            } else {
              that.$toast.fail(res.msg);
            }
          } else {
            that.$toast.fail("未知原因");
          }
        }
        oReqCos.send(form);
      });
    },

    //加载图片
    loadPics(that, res) {
      if(res.samplePic && res.samplePic != "") {
        getUploadKey({
          type: "YPSJD"
        }, tokenRes => {
          that.samplePicPreview.splice(0, that.samplePicPreview.length);
          let samplePicUrl  = exportBaseUrl("res") + "/res/" + res.samplePic + '?accessToken=' + tokenRes.accessToken;
          that.samplePicPreview.push(samplePicUrl);
        });
      }
      if(res.productPic && res.productPic != "") {
        getUploadKey({
          type: "YPSJD"
        }, tokenRes => {
          that.productPicPreview.splice(0, that.productPicPreview.length);
          let samplePicUrl  = exportBaseUrl("res") + "/res/" + res.productPic + '?accessToken=' + tokenRes.accessToken;
          that.productPicPreview.push(samplePicUrl);
        });
      }
    },

    /* 出库-销布 */
    productClothOutByDestroyFn(cloth) {
      const that = this;
      that.$dialog.confirm({
        title: "操作确认",
        message: "将出库当前布匹",
      }).then(() => {
        productClothOutByDestroy({
          clothId: cloth.id,
          flag: 1
        }, () => {
          that.$toast.success("操作成功");
          cloth.status = 94;
        });
        // on confirm
      }).catch(() => {
      });
    },

    /* 销布-入库 */
    productClothInByDestroyFn(cloth) {
      const that = this;
      that.$dialog.confirm({
        title: "操作确认",
        message: "将取消销布操作,入库当前布匹",
      }).then(() => {
        productClothInByDestroy({
          clothId: cloth.id
        }, () => {
          that.$toast.success("操作成功");
          cloth.status = 2;
        });
        // on confirm
      }).catch(() => {
      });
    }
  },
};
</script>

<style lang="scss" scoped>
.product-html {
  width: 100%;
  height: 100%;
  ::v-deep .van-search {
    z-index: 2001;
  }
  .public-scroll {
    //height: calc(100vh - 44px);
    height: 82%;
    width: 100%;
    z-index: 2001;
  }

  .status-out {
    background-color: green;
    color: white;
    ::v-deep .van-cell__value {
      color: white;
    }
  }
}
</style>
